;(function(global){
	var codeMap = ['a','b','c','d','e','f','g','h','i','j'];

	var utils = global.utils = {
		n2s: function(num){
			num = num + '';
			num = num.split('');
			var newArr = [];
			num.forEach(function(v,k){
				newArr.push(codeMap[v]);
			});
			return newArr.join('');
		},
		s2n: function(str){
			str = str + '';
			str = str.split('');
			var newArr = [];
			str.forEach(function(v,k){
				newArr.push(codeMap.indexOf(v));
			});
			return newArr.join('');
		},
		round2: function(num, precision){
			num = num || 0;
			precision = precision || 2;
			var dnum = Math.pow(10, precision);
			if(
				Math.floor(num*dnum*10)%5 == 0 && 
				Math.floor(num*dnum*10) == num*dnum*10 && 
				Math.floor(num*dnum)%2 == 0
				){
				return Math.floor(num*dnum)/dnum;
			}else{
				return Math.round(num*dnum)/dnum;
			}

		},
		obj2qs: function(obj){
			obj = obj || {};
			var qs = '?';
			$.each(obj, function(key, value){
				if(key && value){
					qs += key + '=' + value + '&';	
				}
			});
			return qs.length > 1 ? qs : '';
		},
		linkConvert: function(link, city, name){
		var r = '', qs;
		qs = parseQuery(link);	
		if(/^http/.test(link)){
			r = link;
		}else if(/^inapp:\/\/actlist/.test(link)){
			if(!city){
				r = '/category' + object2query(qs);
			}else{
				r = '/' + city;	
				if(/\d+/.test(qs.genre_id)){
					r += '/category/' + qs.genre_id;
					delete qs.genre_id;
				}else{
					r += '/hot';	
				}
				r += object2query(qs);
			}	
		}else if(/^inapp:\/\/main/.test(link)){
      r = '/search';
		}else if(/^inapp:\/\/act/.test(link) && /\d+/.test(qs.id)){
			r = '/huodong/' + qs.id;	
		}else if(/^inapp:\/\/topic/.test(link) && /\d+/.test(qs.id)){
			r = '/zhuanti/' + qs.id;	
		}else if(/^inapp:\/\/marketing/.test(link) && /\d+/.test(qs.id)){
			r = '/marketing/' + qs.id;	
		}else if(/^inapp:\/\/(user|order|shop|login|topiclist|calendar|dailylist|nearby)/.test(link)){
			r = link;
		}else{
			r = link.replace(/^inapp/, 'http');	
			if(!/^http/.test(r)){
				r = 'http://' + r;	
			}
		}
		if(typeof sticky !== 'undefined' && sticky != ''){
			if(r.indexOf('?') > -1){
				r += '&' + sticky;
			}else{
				r += '?' + sticky;
			}
		}
		return r;
	},
	parseQuery: function(queryString){
		var params = {}, idx;
		queryString = queryString || location.search || '',
		idx = queryString.indexOf('?');
		if(idx > -1){
			queryString = queryString.slice(idx + 1);	
		}else{
			queryString = '';	
		}
		if(queryString){
			queryString = queryString.split('&');
			var i, l, q, key, value;
			for(i = 0, l = queryString.length; i < l; i++){
				q = queryString[i];
				q = q.split('=');
				key = q[0];
				value = q[1];
				params[key] = value;
			}
		}
		return params;
	},
	stickyParams: ['paysource','zmsource','cmbsource','hdl', 'cooper'],
	blockedParams: ['UUID','top_session'],
	getSticky: function(params){
		var sticky = '';
		var keys,k,v;
		keys = Object.keys(params);
		keys.forEach(function(k){
			if(utils.stickyParams.indexOf(k) > -1){
				sticky += '&' + k + '=' + params[k];	
			}	
		});
		return sticky.replace(/^&/,'');
	},
		isPassport: function(str){
			var RE = /[0-9a-zA-Z]{4,32}/;
			if(RE.test(str)) return true;
			return false;
		},
		/**
     * Mobile validation function
     *
     * number in china
     */
    isMobile: function(str){
        //var mobileRE = /^13\d{9}|14[57]\d{8}|15[012356789]\d{8}|18[01256789]\d{8}|170\d{8}$/;
        var mobileRE = /^1[34587]\d{9}$/;
        if(mobileRE.test(str))
            return true;
        return false;
    },

    /**
     * check all number
     *
     */
    isNumber: function(str, num){
        var RE;
        if(!num){
            RE = /^\d+$/;
        }else {
            RE = new RegExp('^\\d\{' + num + '\}$');
        }
        if(RE.test(str))
            return true;
        return false;
    },
    isEmail: function(emailAdress){
        //var emailRE = /^[a-zA-Z0-9-_\.]+@[a-zA-Z0-9-_\.]+$/;
        //var emailRE = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
        var emailRE = /^(?:[-\w])+(?:\.[-\w]+)*@(?:[-\w])+(?:(?:\.[-\w]+)+)$/;
        if(emailAdress && emailRE.test(emailAdress)){
            return true;
        }
        return false;
    },
    showMsg: function(msg, delay){
        var ele = $('<div>');
        if(Browser.platform == 'ios'){
            var top = $(window).scrollTop() + 100;
            ele.attr('class', 'zw-tossMsg-top')
                .css('top', top)
                .text(msg);
        }else{
            ele.attr('class', 'zw-tossMsg')
                .text(msg);
        }
        $('body').append(ele);
        if(delay){
            return setTimeout(function(){
                ele.remove();
            }, delay);
        }
        return ele;
    },
		showMsgDelay: function(msg, delay){
        setTimeout(function(){
            utils.showMsg(msg, delay);
        }, 100);
    },
    getBeginDate: function(){
    	var now = new Date();
    	var year = now.getFullYear();
    	var month = utils.zeroPadding(now.getMonth() + 1, 2);
    	var date = utils.zeroPadding(now.getDate(), 2);
    	return year + '-' + month + '-' + date;
    },
    getEndDate: function(delayMonth){
    	var delayMonth = delayMonth || 3;
    	var now = new Date();
    	var year, month, date;
    	month = now.getMonth();
    	now.setMonth(month + delayMonth);
    	year = now.getFullYear();
    	month = utils.zeroPadding(now.getMonth() + 1, 2);
    	date = utils.zeroPadding(now.getDate(), 2);
    	return year + '-' + month + '-' + date;
    },
    parseDate: function(dates){
        var data = dates;
        var re = /(\d+)-(\d+)-(\d+)/;
        var days = {}, day, key, value, i, l;

        for(i = 0, l = data.length; i < l; i++){
            day = data[i].match(re);
            if(day){
                key = day[1] + day[2];
                value = parseInt(day[3]) + '';
                if(days[key] === undefined){
                    days[key] = [];
                }
                days[key].push(value);
            }
        }
        return days;
    },
    getLocalDateString: function(dateStr){
        var r, t, re, fullYear, month, dateArr, date,  days, day;
        days = ["周日","周一","周二","周三","周四","周五","周六"];
        t = new Date();
        re = /(\d+)-(\d+)-(\d+)/;
        dateArr = dateStr.match(re);
        fullYear = dateArr[1];
        month = dateArr[2] - 0;
        date = dateArr[3] - 0;
        r = '' + fullYear + "年";
        r += month + "月";
        r += date + "日";
        // 避免在设置月日期时出现意外变动，将日期设置为1月1号
        t.setDate(1);
        t.setMonth(0);

        t.setFullYear(fullYear);
        t.setMonth(month - 1);
        t.setDate(date);

        day = t.getDay();
        r += ' ' + days[day];

        return r;
    },
    zeroPadding: function(n, pad){
        var i,l, r = '';
        n = n + '';
        if(n.length < pad){
            l = pad - n.length;
            for(i = 0; i < l; i++){
                r += '0' + n;
            }
        }else{
            r = n;
        }
        return r;
    },
    makeArray: function(str){
        var r = [];
        for(var i = 0, l = str.length; i < l; i++ ){
            r.push(str[i]);
        }
        return r;
    },
    isIdCard: function(num){
    	var idCardRE = /(^\d{15}$)|(^\d{17}([0-9]|[Xx])$)/;
    	if(idCardRE.test(num))
    		return true
    	return false
    },
		json: {
			encode: function(obj){
				var r;
				if(typeof obj !== 'string'){
					try {
						r = JSON.stringify(obj);	
					}catch(err){
						
					}	
				}
				return r ? r : obj;
			},
			decode: function(str){
				var r;
				if(typeof str === 'string'){
					try {
						r = JSON.parse(str);	
					}catch(err){
						
					}	
				}
				return r ? r : str;
			}
		},
		timestamp: function(){
			return Math.round((new Date) / 1000);	
		},
		jstimestamp: function(){
			return +new Date;	
		},
		getuid: function (length) {
			if(typeof length === 'undefined') {
				length = 10;
			}
	
			var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
			var name = '';
			var i = 0;
	
			while(i < length) {
				name += chars[Math.floor((Math.random() * (chars.length-1))+1)];
				i++;
			}
	
			return name;
		},
		getRandomNumber: function(num){
			if(!num || num > 16)
				num = 6;
			var re = new RegExp('0\\\.0*(\\\d{' + num + '})');
			return (Math.random() + "").match(re)[1];
		},
		range: function(num, step){ 
			var r = [];
			var step = step || 1;
			for(var i = 0; i < num; i++){ 
				r[i] = typeof r[i - 1] === 'undefined' ? 0 : r[i - 1] + step; 
			}
			return r;
		},
		random: function(min, max){ 
			if(typeof max === 'undefined'){ 
				max = min;
				min = 0;
			}
			return Math.floor(min + (max - min)*Math.random());
		}
	
	}
	if(typeof Array.prototype.shuffle !== 'function'){
		Array.prototype.shuffle = function(){ 
			var srcArr = this,
				targetArr = [],
				i, length, item, randex, targetLastIndex, switchItem;
			for(i = 0, length = srcArr.length; i < length; i++){ 
				item = srcArr[i];
				targetLastIndex = targetArr.length;
				randex = utils.random(targetLastIndex);
				switchItem = targetArr[randex];
				targetArr[randex] = item;
				typeof switchItem !== 'undefined' && (targetArr[targetLastIndex] = switchItem);
			}
			return targetArr;
		}
	}
})(typeof window !== 'undefined' ? window : this)

